package com.huiminpay.merchant.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.common.cache.execption.BizException;
import com.huiminpay.merchant.common.SecurityUtil;
import com.huiminpay.merchant.convert.MerchantConvert;
import com.huiminpay.merchant.dto.dto.MerchantDTO;
import com.huiminpay.transaction.api.dto.QRCodeDto;
import com.huiminpay.merchant.dto.dto.StoreDTO;
import com.huiminpay.merchant.service.IMerchantService;
import com.huiminpay.merchant.vo.MerchantRegVo;
import com.huiminpay.merchant.vo.MerchantVo;
import com.huiminpay.transaction.api.service.IPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author suozhenhua
 * @since 2021-06-07
 */
@Slf4j
@RestController
@Api(value = "商户操作相关",tags = "商户操作相关",description = "商户操作相关1")
public class MerchantController {
    @Reference
    IPayService payService;
    @Reference
    IMerchantService iMerchantService;
    @Autowired
    RestTemplate restTemplate;
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.domain}")
    private String domain;
//    @GetMapping("/merchant/{id}")
    @GetMapping(value="/my/merchants")
    @ApiOperation(value  = "根据ID查询商户信息")
    //@ApiImplicitParam(name = "id",example = "1",dataType = "Long")
    public MerchantVo findMchById(){
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO mchById = iMerchantService.findMchById(merchantId);
     //MerchantVo merchantVo = new MerchantVo();
    // BeanUtils.copyProperties(mchById,merchantVo);
      MerchantVo merchantVo = MerchantConvert.INSTANCE.DTodaoVo(mchById);

        return merchantVo;
 }
     @PostMapping("merchants/register")
     @ApiOperation(value = "商户注册")

     public MerchantVo reg(@RequestBody MerchantRegVo merchantRegVo){
        //1非空校验
         if (StringUtils.isEmpty(merchantRegVo.getMobile())){
           throw  new  RuntimeException("手机号不能为空");
         }
         if (StringUtils.isEmpty(merchantRegVo.getCode())){
             throw  new  RuntimeException("验证码不能为空");
          }
          if (StringUtils.isEmpty(merchantRegVo.getPassword())){
             throw  new  RuntimeException("密码不能为空");
          }
          if (StringUtils.isEmpty(merchantRegVo.getMobile())){
             throw  new  RuntimeException("用户名不能为空");
          }

         //2验证码校验
         String code = merchantRegVo.getCode();
         String key = merchantRegVo.getKey();
         String url = smsUrl+"/verify?name=sms&verificationCode="+code+"&verificationKey="+key;
         String stringResponseEntity = restTemplate.postForObject(url, null, String.class);
         JSONObject jsonObject = JSONObject.parseObject(stringResponseEntity);
         if (!jsonObject.getBoolean("result")){
             throw new RuntimeException("验证码错误");
         }
         //注册（把数据写入数据库）
         MerchantDTO merchantDto = new MerchantDTO();
         BeanUtils.copyProperties(merchantRegVo,merchantDto);
         merchantDto = iMerchantService.insertReg(merchantDto);
//         MerchantVo merchantVo1 =new MerchantVo();
//         BeanUtils.copyProperties(merchantDto,merchantVo1);

         return MerchantConvert.INSTANCE.DTodaoVo(merchantDto);
     }
      @GetMapping("sms")
      @ApiOperation(value = "短信发送验证码")
      public String smsSend(String phone){
         //短信发送
          //1非空校验
          if (StringUtils.isEmpty(phone)){
              throw  new  RuntimeException("手机号不能为空");
          }
          //发送短信验证码
          String url = smsUrl+"/generate?effectiveTime="+effectiveTime+"&name=sms";

          Map<String,Object> map = new HashMap<>();
          map.put("mobile",phone);//要发送的手机号
          HttpHeaders httpHeaders = new HttpHeaders();
          httpHeaders.add("Content-Type","application/json");
          HttpEntity httpEntity = new HttpEntity(map,httpHeaders);

          String stringResponseEntity = restTemplate.postForObject(url, httpEntity, String.class);
          //{"code":0,"msg":"正常","result":{"key":"sms:b4544e5c01e44f4080e6e86dec97b997","content":null}}
          String key=null;
          try {
              JSONObject jsonObject = JSON.parseObject(stringResponseEntity); //转成JSON对象
              JSONObject result = jsonObject.getJSONObject("result");//获取result 的JSON对象
               key = result.getString("key");
          } catch (Exception e) {
              throw new RuntimeException("验证码发送失败");
          }
           return key;
     }
    @PostMapping("upload")
    @ApiOperation(value = "oss存储")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file==null){
            throw new RuntimeException("文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));

        //文件名
        String fileName=System.currentTimeMillis()+ext;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 填写字符串。

        // 创建PutObjectRequest对象。
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream());

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
        return  domain + fileName;
    }
    @PostMapping("/my/merchants/save")
    @ApiOperation(value = "资质申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantVo",value = "商户认证资料",required =true , dataType = "MerchantVo",paramType = "body")
    })
  public MerchantVo apply(@RequestBody MerchantVo merchantVo){
        //非空校验
        if (StringUtils.isEmpty(merchantVo.getMerchantName())){
            throw new RuntimeException("商户名不能为空");
        }
//        if (StringUtils.isEmpty(merchantVo.getMerchantNo())){
//            throw new RuntimeException("企业编号不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getContactsAddress())){
//            throw new RuntimeException("企业地址不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getMerchantType())){
//            throw new RuntimeException("商户类型不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getBusinessLicensesImg())){
//            throw new RuntimeException("营业执照不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getIdCardFrontImg())){
//            throw new RuntimeException("法人身份证正面照片不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getIdCardAfterImg())){
//            throw new RuntimeException("法人身份证反面照片不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getUsername())){
//            throw new RuntimeException("联系人姓名不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getMobile())){
//            throw new RuntimeException("联系人手机号不能为空");
//        }
//        if (StringUtils.isEmpty(merchantVo.getContactsAddress())){
//            throw new RuntimeException("联系人地址不能为空");
//        }


        //更新数据库
//        MerchantDTO merchantDTO = new MerchantDTO();
//        BeanUtils.copyProperties(merchantVo,merchantDTO);
        MerchantDTO merchantDTO = MerchantConvert.INSTANCE.VodaoDTo(merchantVo);
        Long merchantId= SecurityUtil.getMerchantId();
        merchantDTO.setId(merchantId);
        merchantDTO= iMerchantService.apply(merchantDTO);
      //  BeanUtils.copyProperties(merchantDTO,merchantVo);
        return MerchantConvert.INSTANCE.DTodaoVo(merchantDTO);
    }
    /**
     * 分页查询门店列表
     */
    @PostMapping("my/stores/merchants/page")
    @ApiOperation("分页查询所属门店列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo",value = "页码",example = "1"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",example = "10")
    })
    public PageVO<StoreDTO> queryStoreBypage(@RequestParam Integer pageNo,@RequestParam Integer pageSize){
        Long merchantId = SecurityUtil.getMerchantId();
        return iMerchantService.queryStoreBypage(pageNo,pageSize,merchantId);
    }
    @ApiOperation("生成商户应用门店二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "商户应用id", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "storeId", value = "商户门店id", required = true, dataType = "String", paramType = "path"),
    })
    @GetMapping(value = "/my/apps/{appId}/stores/{storeId}/app-store-qrcode")
    public String createCScanBStoreQRCode(@PathVariable String appId, @PathVariable Long storeId) throws BizException {
       //组合参数
        QRCodeDto qrCodeDto = new QRCodeDto();
        qrCodeDto.setAppId(appId);
        qrCodeDto.setStoreId(storeId);

        qrCodeDto.setStoreId(SecurityUtil.getMerchantId());
        StoreDTO storeDTO =iMerchantService.selectStoreInfoById(storeId);
        qrCodeDto.setBody(storeDTO.getStoreName());
        qrCodeDto.setSubject(storeDTO.getStoreName());
        //生成二维码
        String qestr = payService.createCScanQRCode(qrCodeDto);
        return qestr;
    }
}
